import axios from 'axios'
import cookies from 'vue-cookies'
import qs from 'qs';

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
        //  从cookie中获取token
        let userToken = cookies.get("user_token");
        if (!userToken) {
            alert("请先登录");
            //  测试token
            userToken = "Ry0vfSJtb2JpbGUiOiIxODk4MzA5NTQyNyIsInBhc3N3b3JkIjoiNTBiNTFhMmY5NmJmMWJmN2E0NDI2MGVlN2U1YTUxZjIiLCJjb2RlIjoiMDA1MDBjNzIie2dLWg%3D%3D";
            // TODO 如果token不存在则跳转到登录页面
            window.location.href = "/login";
        }
        //  装填token参数,格式化post数据
        if (config.method !== "get" && config.data) {
            config.data['token'] = userToken;
            config.data = qs.stringify(config.data);
        }
        return config
    },
    error => {
        // do something with request error
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        // if the custom code is not 20000, it is judged as an error.
        if ((res.error && res.error !== 0) || (res.status && res.status !== 1)) {
            console.log("请求错误", res);
            //  如果用户失效或登录失败,则重新登录
            if ((res.status && res.status === 2)) {
                window.location.href = "/login"
            } else {
                return Promise.reject(new Error(res.message || 'Error'))
            }
        } else {
            return res.data
        }
    },
    error => {
        console.log("错误");
        return Promise.reject(error)
    }
)

export default service
